/**
 * 
 */
$.fn.searchStringWidget = function(options){
	var $this = this;
	options = options || {};
	options.iconUrl = options.iconUrl || './images/icons/auto/';
	
	$this._init = function(){
		
	};
	$this._bindEvents = function(){
		/* -------------------------------- */
		$this.autocomplete({
			minLength: 0,
			source: function(request, response) {
				/* delegate back to autocomplete, but extract the last term
				 * response($.ui.autocomplete.filter(availableTags, extractLast(request.term))); */
				 
				$.ajax({
						url: "ajax/search",
						dataType: "json",
						data: {
							featureClass: "P",
							style: "full",
							maxRows: 12,
							q: $this.extractLast( request.term )
						},
						success: function(data) {
							response($.map(data, function(item) {
								
								// @todo Переробити ці граблі
								var delim = '';
								if(1==item.param)delim = '<img src="'+options.iconUrl+'make-icon.gif">';
								if(2==item.param)delim = '<img src="'+options.iconUrl+'make-icon.gif">';
								if(3==item.param || 4==item.param)delim = '<img src="'+options.iconUrl+'city-icon.gif">';
								if(5==item.param)delim = '<img src="'+options.iconUrl+'price-icon.gif">';
								if(6==item.param)delim = '<img src="'+options.iconUrl+'date.jpg">';
								if(9==item.param)delim = '<img src="'+options.iconUrl+'color_wheel.png">';
								if(10==item.param)delim = '<img src="'+options.iconUrl+'sedan.jpg">';
								if(11==item.param)delim = '<img src="'+options.iconUrl+'transmission-icon.gif">';
								
								//param_type
								
								return {
									label: delim + item.name + (item.param_name ? " (" + item.param_name +")" : ""),
									value: item.name
								};
							}));
						}
					});
				
				
				
			},
			focus: function() {
				return false;
			},
			search: function() {
				var term = $this.extractLast( this.value );
				if ( term.length < 2 ) {
					return false;
				}
			},
			select: function(event, ui) {
				var terms = $this.split( this.value );
				terms.pop();
				terms.push( ui.item.value );
				terms.push("");
                this.value = terms.join(" ");
				return false;
			}
		});
		/* -------------------------------- */
	};
	
	/**
	 * 
	 */
	$this.split = function(val) {
		return val.split(/\s{1,}/);
	};
	/**
	 * 
	 */
	$this.extractLast = function(term) {
		return $this.split(term).pop();
	};
	/**
	 * Implementation
	 */
	$this._init();
	$this._bindEvents();
	
	return $(this);
};


/**
 * Some utils
 */
$('#input_text').keyup(function(e) {
	//alert(e.keyCode);
	if(e.keyCode == 13) {
		alert('Enter key was pressed.');
	}
});